<template>
  <div class="table-classic-wrapper">
    <el-card class="card_box_shoppingRecord" shadow="always">
      <!--购买记录表格-->
      <el-table
          :data="shoppingRecordList"
          @selection-change="handleSelectionChange"
          stripe
          :cell-style="{textAlign: 'center'}"
          :header-cell-style="{textAlign: 'center'}"
          style="width: 100%;"
          class="table-inline-edit">

        <el-table-column type="selection" width="50"/>

        <el-table-column
            label="购买时间">
          <template slot-scope="scope">
            {{ format(new Date(scope.row.gmtCreate)) }}
          </template>
        </el-table-column>

        <el-table-column
            prop="text"
            label="美食名称">
        </el-table-column>

        <el-table-column
            prop="type"
            label="美食类别">
        </el-table-column>

        <el-table-column
            prop="purchaseCount"
            label="购买数量">
        </el-table-column>

        <el-table-column
            prop="orderState"
            label="配送状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.orderState===0">未接单</el-tag>
            <el-tag type="success" v-if="scope.row.orderState===1">已接单</el-tag>
            <el-tag type="danger" v-if="scope.row.orderState===2">待取餐</el-tag>
            <el-tag type="warning" v-if="scope.row.orderState===3">正在路上</el-tag>
            <el-tag type="primary" v-if="scope.row.orderState===4">抵达用户</el-tag>
            <el-tag v-if="scope.row.orderState===5">已接收</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="totalPrice"
            label="开销">
          <template slot-scope="scope">
            {{scope.row.totalPrice | numFilter}}
          </template>
        </el-table-column>

        <el-table-column
            prop="delivery"
            label="配送费">
        </el-table-column>

        <el-table-column
            width="100px"
            label="送达时间">
          <template slot-scope="scope">
            <div v-if="scope.row.orderState>=2">
              {{ format(new Date(scope.row.gmtUpdate)) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
            label="确认送达">
          <template slot-scope="scope">

            <el-button type="primary" slot="reference" size="mini" :disabled="scope.row.orderState !== 4"
                       @click="confirmAccept(scope.row)">
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <Pagination :total="total" :page="currentPage" :limit="pageSize" @pagination="handlePageChange"></Pagination>
    </el-card>

    <!--商品评论对话框-->
    <!--
    在遮罩空白处点击。可以通过:close-on-click-modal='false'来关闭这个功能
    按下esc键。可以通过:close-on-press-escape='false'来关闭这个功能
    点击右上角的X按钮。可以通过:show-close="false"来隐藏这个按钮
    -->
    <el-dialog
        title="美食评论"
        :visible.sync="showComment"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="35%">
      <el-form :model="comments" ref="addComment" label-width="100px">

        <el-form-item
            label="美食评价"
            prop="appraiseScore">
          <el-rate
              v-model="comments.appraiseScore"
              show-score
              style="margin-top: 10px">
          </el-rate>
        </el-form-item>

        <el-form-item
            label="商家服务评价"
            prop="appraiseServe">
          <el-rate
              v-model="comments.appraiseService"
              show-score
              style="margin-top: 10px">
          </el-rate>
        </el-form-item>

        <el-form-item
            label="我的评论"
            prop="appraiseInformation"
            :rules="[{ required: true, message: '评论不能为空'}]">

          <el-input
              v-model="comments.appraiseInformation"
              type="textarea"
              placeholder="请填写美食评价"
              maxlength="80"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 6}"
              style="width: 80%;margin-top: 10px">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddComment">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/component/pagination/Pagination";
import {getPurchaseByUserId, confirmPurchaseUpdate} from "@/api/user/comprehensive/purchase";
import {getUserInformation} from "@/api/user";
import {insertInformationByUserAndCommodity} from "@/api/user/information";
import {getGeneralUserById} from "@/api/general/userGeneral";

export default {
  name: "ShoppingRecord",

  components: {
    Pagination
  },

  data() {
    return {

      /**
       * 评论弹框的显示
       */
      showComment: false,

      /**
       * 用户评论
       * appraiseService:餐厅服务评价，1-5分
       * appraiseInformation：美食评价（文字评价）
       */
      comments: {
        appraiseScore: null,
        appraiseService: null,
        appraiseInformation: '',
        price: null,
        userId: null,
        commodityId: null,
      },

      /**
       * 根据交易状态展示的购买记录
       */
      option: '4',

      total: 0,//订单总数
      currentPage: 0,//当前页码
      pageSize: 6,//每页显示条数

      originalTotal: 0,//原始订单总数

      /**
       * 多选数据暂存数组
       */
      multipleSelection: [],

      /**
       * 用户已购美食信息列表
       */
      shoppingRecordList: [],

      /**
       * 当前用户
       */
      user: undefined,
    }
  },

  created() {
    this.getGeneralUserById();
  },

  filters: {

    numFilter (value) {
      // 截取当前数据到小数点后两位
      return parseFloat(value).toFixed(2)
    }

  },

  methods: {

    /**
     * 根据购买美食的用户id分页查询购买信息
     */
    getShoppingRecordList() {
      const formData = new FormData();

      formData.append("currentPage", this.currentPage);
      formData.append("pageSize", this.pageSize);
      formData.append("userId", this.user.id);

      getPurchaseByUserId(formData).then(res => {
        this.shoppingRecordList = res.information;
        this.total = res.total;
        this.originalTotal = this.total;
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })

    },

    /**
     * 获得用户信息
     */
    getGeneralUserById() {
      const user = eval('(' + getUserInformation() + ')');

      const formData = new FormData();

      formData.append("id", user.id);


      getGeneralUserById(formData).then(res => {
        this.user = res.user;
        this.getShoppingRecordList();
      }).catch(() => {
        this.$message.error("用户信息获取失败");
      })
    },

    /**
     * 修改购买日期格式
     */
    format(date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();

      if (month < 10) {
        month = '0' + month;
      }

      if (day < 10) {
        day = '0' + day;
      }

      if (hour < 10) {
        hour = '0' + hour;
      }

      if (minute < 10) {
        minute = '0' + minute;
      }

      if (second < 10) {
        second = '0' + second;
      }

      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },

    /**
     * 更新用户对应的订单信息的状态
     */
    confirmAccept(row) {
      const formData = new FormData();

      var orderState = '5';

      formData.append("id", row.id);
      formData.append("orderState", orderState);

      confirmPurchaseUpdate(formData).then(res => {
        if (res.message === 1 && res.wallet === 1) {

          this.getShoppingRecordList();
          this.comments.userId = row.userId;
          this.comments.commodityId = row.commodityId;
          this.comments.price = row.price;
          this.showComment = true;
        }
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })
    },

    /**
     * 提交用户评论
     */
    submitAddComment() {
      this.$refs.addComment.validate(valid => {
        const formData = new FormData();
        formData.append("appraiseInformation", this.comments.appraiseInformation);
        formData.append("appraiseService", this.comments.appraiseService);
        formData.append("appraiseScore", this.comments.appraiseScore);
        formData.append("price", this.comments.price);
        formData.append("userId", this.comments.userId);
        formData.append("commodityId", this.comments.commodityId);

        if (valid) {
          insertInformationByUserAndCommodity(formData).then(res => {
            if (res.message === 1 && res.commodityMessage === 1) {
              this.$message.success("提交成功");
              this.showComment = false;
              this.getShoppingRecordList();

              this.comments.appraiseScore=0;
              this.comments.appraiseService=0;
              this.comments.appraiseInformation=null;
            }
          }).catch(() => {
            this.$message({
              message: "error",
              type: "error"
            })
          })
        }
      })
    },

    /**
     * 多选操作，与multipleSelection相对应
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * 处理分页
     */
    handlePageChange(val) {
      this.currentPage = val.page;
      if (this.originalTotal === this.total) {
        this.getShoppingRecordList();
      } else {
        this.changeOption();
      }

    },

    /**
     * 修改收货时间格式
     */
    formatDate(date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();

      if (month < 10) {
        month = '0' + month;
      }

      if (day < 10) {
        day = '0' + day;
      }

      if (hour < 10) {
        hour = '0' + hour;
      }

      if (minute < 10) {
        minute = '0' + minute;
      }

      if (second < 10) {
        second = '0' + second;
      }

      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },
  }
}
</script>

<style lang="less">
.card_box_shoppingRecord {
  height: 75vh;
  margin: 5px 5px;
}

.el-input__icon {
  cursor: pointer;
}
</style>
